package info.niwota.group;

import info.niwota.group.note.GreetingListActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Etalk - talk over email
 * 
 * Send audio message over email.
 * 
 * Your friend does not have to own a phone or use one to hear you; you can talk
 * to anyone with an email address and all day long for free.
 * 
 * It's as easy as: touch an email address, record your voice, and send!
 * 
 * You can certainly do better talking than typing on a device about the size of
 * your palm.
 * 
 * If you prefer Gmail over text editors for messaging, use Etalk not just any
 * voice recorder for talking.
 * 
 * Features:
 * 
 * Full integration with built-in contacts app (email address) and media store
 * (music playlist) for your voice recording playback Email address sorted by
 * starred, name, or last time called, in ascending/descending order. Email
 * group/list support Copy/extract/paste email addresses to/from clipboard
 * Balanced index navigation in stead of scrolling a long contact list Create
 * shortcut to audio composer or playlist
 * 
 * detect new address/voice comments on any web URL
 * 
 * @author qiangli
 */
public class EtalkContactsActivity extends ListActivity {
	private static final String HOME_URI = "file:///android_asset/home.html";

	private static final String TAG = "EtalkContactsActivity";

	private static final int MENU_COMPOSE = R.id.contacts_compose_opt_menu_id;
	private static final int MENU_GREETING = R.id.contacts_greeting_opt_menu_id;
	private static final int MENU_NEWCONTACT = R.id.contacts_newcontact_opt_menu_id;
	private static final int MENU_NEWLIST = R.id.contacts_newlist_opt_menu_id;
	private static final int MENU_SENT = R.id.contacts_sent_opt_menu_id;
	private static final int MENU_SETUP = R.id.contacts_setup_opt_menu_id;

	private static final int RC_EDITRECIPIENTS = 7;
	private static final int RC_NEWCONTACT = 3;
	private static final int RC_PLAYLIST = 6;
	private static final int RC_PLAYLISTS = 2;
	private static final int RC_RECORD = 1;
	private static final int RC_SETUP = 5;
	private static final int RC_VIEWCONTACT = 4;
	private static final int RC_ATTACH = 8;
	private static final int RC_GREETING = 9;
	private static final int RC_COMPOSEWITH = 10;

	//private static final int DIALOG_SEND = 1;

	public static final int DIALOG_PROGRESS_LOADING = 1;

	private ContactListAdapter adapter;

	private MenuItem composeMenuItem;
	private MenuItem newContactMenuItem;
	private MenuItem newListMenuItem;
	private MenuItem sentMenuItem;
	private MenuItem setupMenuItem;

	private ImageButton compass;

	private EmailContact selectedItem;

	private ProgressDialog loadProgressDialog;

	private ImageButton mode;

	private int etalkMode;

	private Toast toast;

	private static final int[] MODE_DRAWS  = new int[] {R.drawable.icon, R.drawable.camera, R.drawable.video};

	private static final int[] MODE_MSGS = new int[] {R.string.msg_mode_etalk, R.string.msg_mode_photo, R.string.msg_mode_video};


	private void buildComposeMenuItem(MenuItem mi, long cid, String name, String emails) {
		switch(etalkMode) {
		case 1:
			buildAttachMenuItem(mi, EtalkIntent.ACTION_PICTURE_COMPOSE,  cid, name, emails);
			break;
		case 2:
			buildAttachMenuItem(mi, EtalkIntent.ACTION_VIDEO_COMPOSE, cid, name, emails);
			break;
		default:
			//0 and others
			buildEtalkMenuItem(mi, cid, name, emails);
		}
	}
	
	private void buildComposeWithMenuItem(MenuItem mi, long cid, String name, String emails) {
		switch(etalkMode) {
		case 1:
			buildAttachMenuItem(mi, EtalkIntent.ACTION_PICTURE_COMPOSEWITH,  cid, name, emails);
			break;
		case 2:
			buildAttachMenuItem(mi, EtalkIntent.ACTION_VIDEO_COMPOSEWITH, cid, name, emails);
			break;
		default:
			buildEmailMenuItem(mi, cid, name, emails);
		}
	}

	private void buildEmailMenuItem(MenuItem mi, long cid, String name,
			String emails) {
		Intent i = new Intent(this, EmailActivity.class);
		i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra(EtalkIntent.EXTRA_EMAIL, emails);
		i.putExtra(EtalkIntent.EXTRA_CONTACTID, cid);
		//
		mi.setIntent(i);
		mi.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Intent i = item.getIntent();
				startActivityForResult(i, RC_COMPOSEWITH);
				return true;
			}
		});
	}

	private void buildEtalkMenuItem(MenuItem mi, long cid, String name, String emails) {
		Intent i = new Intent(this, EtalkActivity.class);
		i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra(EtalkIntent.EXTRA_EMAIL, emails);
		i.putExtra(EtalkIntent.EXTRA_CONTACTID, cid);
		//
		mi.setIntent(i);
		mi.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Intent i = item.getIntent();
				startActivityForResult(i, RC_RECORD);
				return true;
			}
		});
	}

	private void buildAttachMenuItem(MenuItem mi, String action, long cid, String name, String emails) {
		Intent i = new Intent(this, AttachActivity.class);
		i.setAction(action);
		i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra(EtalkIntent.EXTRA_EMAIL, emails);
		i.putExtra(EtalkIntent.EXTRA_CONTACTID, cid);
		//
		mi.setIntent(i);
		mi.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				Intent i = item.getIntent();
				startActivityForResult(i, RC_ATTACH);
				return true;
			}
		});
	}

	private EmailContact getItem(int pos) {
		return (EmailContact) getListAdapter().getItem(pos);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "onActivityResult requestCode: " + requestCode  + " resultCode: " + resultCode + " == "+ RESULT_OK +  " data: " + data);
		}
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case RC_EDITRECIPIENTS:
				break;
			case RC_GREETING:
				break;
			case RC_NEWCONTACT:
				break;
			case RC_VIEWCONTACT:
				break;
			case RC_RECORD:
				break;
			case RC_COMPOSEWITH:
				break;
			case RC_ATTACH:
				break;
			case RC_PLAYLIST:
				return;
			case RC_PLAYLISTS:
				return;
			default:
				return;
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		//
		//NOTE call refresh() if any change made to contacts directly without starting an activity
		//
		EmailContact ec = selectedItem;
		if (ec == null) {
			return false; //not reachable
		}
		int id = item.getItemId();
		switch (id) {
		case R.id.compose_context_menu_id: {
			MenuItem addr = item;
			SubMenu sm = addr.getSubMenu();
			sm.clear();
			MenuItem all = sm.add(ec.name);
			buildComposeMenuItem(all, ec.id, ec.name, Utils.toString(ec.emails));
			if (ec.emails.length > 1) {
				for (String s : ec.emails) {
					MenuItem smi = sm.add(s);
					buildComposeMenuItem(smi, -1, null, s); //unknown cid
				}
			} 
			break;
		}
		case R.id.composewith_context_menu_id: {
			MenuItem addr = item;
			SubMenu sm = addr.getSubMenu();
			sm.clear();
			MenuItem all = sm.add(ec.name);
			buildComposeWithMenuItem(all, ec.id, ec.name, Utils.toString(ec.emails));
			if (ec.emails.length > 1) {
				for (String s : ec.emails) {
					MenuItem smi = sm.add(s);
					buildComposeWithMenuItem(smi, -1, null, s);
				}
			} 
			break;
		}
		case R.id.copy_context_menu_id: {
			Utils.copyToClipboard(this, ec);
			CharSequence text = getString(R.string.msg_copied, ec.emails.length);
			Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
			break;
		}
		case R.id.paste_context_menu_id: {
			int cnt = Utils.pasteFromClipboard(this, ec);
			CharSequence text = null;
			if (cnt == 0) {
				text = getString(R.string.msg_pasted_none);
			} else {
				text = getString(R.string.msg_pasted, cnt);
				refresh();
			}
			Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
			break;
		}
		case R.id.playlist_context_menu_id: {
			startPlaylistActivity(ec);
			break;
		}
		case R.id.shortcut_context_menu_id: {
			doCreateShortcut(ec);
			break;
		}
		case R.id.viewcontact_context_menu_id: {
			startViewContactActivity(ec.id);
			break;
		}
		case R.id.contacts_viewlist_context_menu_id: {
			startViewRecipientsActivity(ec);
			break;
		}
		case R.id.contacts_starlist_context_menu_id: {
			doStarList(ec);
			break;
		}
		case R.id.contacts_removelist_context_menu_id: {
			doRemoveList(ec);
			break;
		}
		default:
		}
		return true;
	}

	private void doStarList(final EmailContact ec) {
		final Context ctx = this;
		final CharSequence t = getString(R.string.title_star_item, ec.name);
		int star = ec.getStarred();
		final Dialog[] d = new Dialog[1];
		d[0] = new AlertDialog.Builder(ctx)
        .setTitle(t)
        .setSingleChoiceItems(R.array.star_dialog_items, star, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
        		ContactUtils.toggleStar(ctx, ec, which);
        		d[0].dismiss();
        		//
        		reload();
            }
        })
        .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        })
        .create();
		d[0].show();
	}

	private void doRemoveList(final EmailContact ec) {
		final Context ctx = this;
		final CharSequence t = getString(R.string.title_remove_item, ec.name);
		Dialog d = new AlertDialog.Builder(ctx)
        .setTitle(t)
        .setMessage(R.string.text_are_you_sure)
        .setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
        		ContactUtils.remove(ctx, ec);
        		reload();
            }
        })
        .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        })
        .create();
		d.show();
	}

	private void reload() {
		try {
			adapter.reload(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void refresh() {
		try {
			adapter.refresh();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doCreateShortcut(final EmailContact ec) {
		final AlertDialog.Builder b = new AlertDialog.Builder(this);
		final int len = ec.emails.length;
		final String[] items = new String[len + 1];
		items[0] = ec.name;
		System.arraycopy(ec.emails, 0, items, 1, len);
		b.setTitle(R.string.menu_shortcut);
		b.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				createShortcut(ec, which);
			}
		});
		final AlertDialog d = b.create();
		d.show();
	}

	private void createShortcut(EmailContact ec, int which) {
		long id = (which == 0 ? ec.id : -1);
		String lsname = (which == 0 ? ec.name : null);
		String email = (which == 0 ? null : ec.emails[which - 1]);
		//TODO prompt for shortcut name and icon/create icon from photo
		String shortcut = (which == 0 ? ec.name : ec.name + "-" + email);	
		//
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "create shortcut: " + shortcut + " id: "+ id + " email: " + email);
		}
		//
		Shortcuts.createRecordShortcut(this, shortcut, id, lsname, email);
	}

	private ProgressDialog createLoadProgressDialog() {
		ProgressDialog pd = new ProgressDialog(this);
		pd.setMessage(getText(R.string.status_loading));
		pd.setIndeterminate(true);
		pd.setCancelable(false);
		return pd;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		final Intent intent = getIntent();
		final String action = intent.getAction();
		if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
			Shortcuts.setupShortcut(this, EtalkContactsActivity.class,
					getString(R.string.app_name), R.drawable.icon);
			finish();
			return;
		}
		//
		//requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		//requestWindowFeature(Window.FEATURE_LEFT_ICON);
		setTheme(android.R.style.Theme_Translucent_NoTitleBar);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.etalkcontacts);
		//setProgressBarIndeterminate(true);
		setTitle(R.string.app_contacts);
		//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
		//		R.drawable.etalk25);
		//
		ListView lv = getListView();
		lv.setFastScrollEnabled(true);
		registerForContextMenu(lv);
		//
		ImageButton byName = (ImageButton) findViewById(R.id.byNameButton);
		byName.setFocusable(true);
		ImageButton byStar = (ImageButton) findViewById(R.id.byStarButton);
		byStar.setFocusable(true);
		ImageButton byTime = (ImageButton) findViewById(R.id.byTimeButton);
		byTime.setFocusable(true);
		compass = (ImageButton) findViewById(R.id.compassButton);
		compass.setFocusable(true);
		compass.setImageResource(R.drawable.compass_disabled);
		//
		mode = (ImageButton) findViewById(R.id.modeButton);
		mode.setFocusable(true);
		//
		TextView footer = (TextView) findViewById(R.id.footer);
		//
		OnClickListener l = new OnClickListener() {
			public void onClick(View v) {
				final int id = v.getId();
				switch(id) {
				case R.id.compassButton:
					showIndex();
					break;
				case R.id.modeButton:
					changeMode();
					break;
				case R.id.footer:
					etalkSupport();
					break;
				default:
					doSort(id);
				}
			}
		};
		byName.setOnClickListener(l);
		byStar.setOnClickListener(l);
		byTime.setOnClickListener(l);
		compass.setOnClickListener(l);
		footer.setOnClickListener(l);
		mode.setOnClickListener(l);
		//
		initAdapter();
		//
	}

	private void doSort(int id) {
		try {
			adapter.doSort(this, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initAdapter() {
		adapter = new ContactListAdapter();
		adapter.init(this);
		//
		adapter.invalidate();
		//
		setListAdapter(adapter);
	}

	private void showIndex() {
		try {
			NameIndex.showIndex(this, adapter, getListView());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.contacts, menu);
		//
		AdapterView.AdapterContextMenuInfo cmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
		int pos = cmi.position;
		selectedItem = getItem(pos);
		//
		EmailContact ec = selectedItem;
		menu.setHeaderTitle(ec.name);
		//
		MenuItem paste = menu.findItem(R.id.paste_context_menu_id);
		boolean canPaste = (Utils.noEmailOnClipboard(this) == false);
		paste.setEnabled(canPaste);
		//
		MenuItem copy = menu.findItem(R.id.copy_context_menu_id);
		boolean hasEmail = (ec.emails != null && ec.emails.length > 0);
		copy.setEnabled(hasEmail);
		//
		MenuItem pl = menu.findItem(R.id.playlist_context_menu_id);
		pl.setEnabled(true);
		//
		MenuItem cm = menu.findItem(R.id.viewcontact_context_menu_id);
		MenuItem lm = menu.findItem(R.id.emaillist_context_menu_id);
		boolean grp = (ec.id < -1);
		cm.setVisible(!grp);
		boolean ls = ec.name.startsWith("@") || grp;
		lm.setVisible(ls);
		lm.getSubMenu().setGroupVisible(R.id.CONTACTS_LIST_MENU, grp);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_PROGRESS_LOADING:
			loadProgressDialog = createLoadProgressDialog();
			return loadProgressDialog;
		default:
		}
		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.contacts_options, menu);
		//
		composeMenuItem = menu.findItem(R.id.contacts_compose_opt_menu_id);
		sentMenuItem = menu.findItem(R.id.contacts_sent_opt_menu_id);
		newContactMenuItem = menu.findItem(R.id.contacts_newcontact_opt_menu_id);
		newListMenuItem = menu.findItem(R.id.contacts_newlist_opt_menu_id);
		setupMenuItem = menu.findItem(R.id.contacts_setup_opt_menu_id);
		return true;
	}

	@Override
	protected void onListItemClick(ListView lv, View v, int pos, long id) {
		EmailContact ec = getItem(pos);
		String name = ec.name;
		String emails = Utils.toString(ec.emails);
		doEtalk(ec.id, name, emails);
	}

	private void doEtalk(long cid, String name, String emails) {
		switch(etalkMode) {
		case 1:
			startAttachActivity(EtalkIntent.ACTION_PICTURE_COMPOSE, cid, name, emails);
			break;
		case 2:
			startAttachActivity(EtalkIntent.ACTION_VIDEO_COMPOSE, cid, name, emails);
			break;
		default:
			//0 and others
			startRecordActivity(cid, name, emails);
		}
	}
	
//	private void doEmail(long cid, String name, String emails) {
//		switch(etalkMode) {
//		case 1:
//			startAttachActivity(EtalkIntent.ACTION_PICTURE, cid, name, emails, EtalkIntent.ACTION_COMPOSE);
//			break;
//		case 2:
//			startAttachActivity(EtalkIntent.ACTION_VIDEO, cid, name, emails, EtalkIntent.ACTION_COMPOSE);
//			break;
//		default:
//			startEmailActivity(name, emails);
//		}
//	}

//	private void startEmailActivity(String name, String emails) {
//		try {
//			String subj = Preferences.getGreetingSubject(this, "");
//			String msg = Preferences.getGreetingBody(this, "");
//			MailTemplate.startSendActivity(this, name, emails, subj, msg, null, null);
//		} catch (ActivityNotFoundException e) {
//			toast(R.string.msg_noapp, e.getMessage(), Toast.LENGTH_LONG);
//		} catch (Exception e) {
//			toast(R.string.msg_fail, e.getMessage(), Toast.LENGTH_LONG);
//		}
//	}

//	private void toast(int resId, String arg, int duration) {
//		CharSequence text = getString(resId, arg);
//		Toast.makeText(this, text, duration).show();
//	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case MENU_COMPOSE:
			startComposeActivity();
			return true;
		case MENU_GREETING:
			startGreetingActivity();
			return true;
		case MENU_NEWLIST:
			startEditRecipientsActivity();
			return true;
		case MENU_NEWCONTACT:
			startNewContactActivity();
			return true;
		case MENU_SENT:
			startPlaylistsActivity();
			return true;
		case MENU_SETUP:
			startSetupActivity();
			return true;
		}
		return false;
	}

	@Override
	protected void onPause() {
		super.onPause();
		//
		try {
			adapter.saveSortSettings(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		composeMenuItem.setEnabled(true);
		newContactMenuItem.setEnabled(true);
		newListMenuItem.setEnabled(true);
		sentMenuItem.setEnabled(true);
		setupMenuItem.setEnabled(true);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		//
		try {
			adapter.restoreSortSettings(this);
			//
			//
			adapter.reload(this);
			//
			updateMode(); //mode may have changed (in audio composer)
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle state) {
		super.onRestoreInstanceState(state);
		//
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "onRestoreInstanceState: " + state);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		//
		if (Constants.DEBUG_ENABLED) {
			Log.d(TAG, "onSaveInstanceState: " + outState);
		}
	}

	private void updateMode() {
		etalkMode = Preferences.getEtalkMode(this, 0);
		etalkMode %= MODE_DRAWS.length; //just to be sure
		mode.setImageResource(MODE_DRAWS[etalkMode]);
	}

	private void startComposeActivity() {
		doEtalk(-1, null, null);
	}

	private void startEditRecipientsActivity() {
		Intent i = new Intent(this, RecipientsActivity.class);
		startActivityForResult(i, RC_EDITRECIPIENTS);
	}

	private void startViewRecipientsActivity(EmailContact ec) {
		Intent i = new Intent(this, RecipientsActivity.class);
		i.putExtra(EtalkIntent.EXTRA_EMAILS, Utils.toString(ec.emails));
		i.putExtra(EtalkIntent.EXTRA_LISTNAME, ec.name);
		startActivityForResult(i, RC_EDITRECIPIENTS);
	}

	private void startAttachActivity(String action, long cid, String name, String emails) {
		Intent i = new Intent(this, AttachActivity.class);
		i.setAction(action);
		i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra(EtalkIntent.EXTRA_EMAIL, emails);
		i.putExtra(EtalkIntent.EXTRA_CONTACTID, cid);
		//
		startActivityForResult(i, RC_ATTACH);
	}

	private void startGreetingActivity() {
		Intent i = new Intent(this, GreetingListActivity.class);
		startActivityForResult(i, RC_GREETING);
	}

	private void startRecordActivity(long cid, String name, String email) {
		Intent i = new Intent(this, EtalkActivity.class);
		i.putExtra(EtalkIntent.EXTRA_NAME, name);
		i.putExtra(EtalkIntent.EXTRA_EMAIL, email);
		i.putExtra(EtalkIntent.EXTRA_CONTACTID, cid);
		//
		startActivityForResult(i, RC_RECORD);
	}

	private void startNewContactActivity() {
		Intent i = new Intent(Intent.ACTION_INSERT);
		i.setType(Contacts.People.CONTENT_ITEM_TYPE);
		i.setData(Contacts.People.CONTENT_URI);
		startActivityForResult(i, RC_NEWCONTACT);
		////2.0 Intent i = new Intent(Intents.Insert.ACTION, Contacts.CONTENT_URI);
	}

	private void startPlaylistsActivity() {
		Intent i = new Intent(this, PlaylistActivity.class);
		startActivityForResult(i, RC_PLAYLISTS);
	}

	private void startPlaylistActivity(EmailContact ec) {
		Intent i = new Intent(this, PlaylistActivity.class);
		i.putExtra(PlaylistActivity.EXTRA_PLAYLIST, ec.name);
		startActivityForResult(i, RC_PLAYLISTS);
	}

	private void startSetupActivity() {
		Intent i = new Intent(this, SetupActivity.class);
		i.putExtra(SetupActivity.EXTRA_TAB, SetupActivity.TAB_ACCOUNT);
		startActivityForResult(i, RC_SETUP);
	}

	private void startViewContactActivity(long cid) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		Uri uri = Contacts.People.CONTENT_URI.buildUpon().appendPath(cid + "")
				.build();
		i.setData(uri);
		startActivityForResult(i, RC_VIEWCONTACT);
	}

	public void showCompass(boolean b) {
		compass.setEnabled(b);
		int rid = (b ? R.drawable.compass : R.drawable.compass_disabled);
		compass.setImageResource(rid);
	}
	
	private void etalkSupport() {
		try {
			Intent i = new Intent(this, WebViewActivity.class);
			i.setData( Uri.parse(HOME_URI));
			startActivity(i);
		} catch (Exception e) {
			//
		}
	}

	private void toast(int resId, int duration) {
		if (toast != null) {
			try {
				toast.cancel();
			} catch (Exception e) {
				//e.printStackTrace();
			}
		}
		toast = Toast.makeText(this, resId, duration);
		toast.show();
	}

	private void changeMode() {
		try {
			int m = (etalkMode + 1) % 3;
			mode.setImageResource(MODE_DRAWS[m]);
			toast(MODE_MSGS[m], Toast.LENGTH_SHORT);
			Preferences.putEtalkMode(this, m);
			etalkMode = m;
		} catch (Exception e) {
			//
		}
	}
}
